package com.zhehekeji.opsys.api.plugin.wechat.util;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName FileUtils
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2018-1-18   上午10:10:23
 */
public abstract class FileUtils {
	
	public static void download(String srcUrl, String destPath) throws Exception{
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;
		byte[] buf = new byte[1024];
		int size = 0;
		try {
			url = new URL(srcUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(destPath);
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			fos.flush();
		} catch (Exception e) {
			try{
				url = new URL(srcUrl);
				httpUrl = (HttpURLConnection) url.openConnection();
				httpUrl.connect();
				bis = new BufferedInputStream(httpUrl.getInputStream());
				fos = new FileOutputStream(destPath);
				while ((size = bis.read(buf)) != -1) {
					fos.write(buf, 0, size);
				}
				fos.flush();
			}catch(Exception e1){
				throw e1;
			}
		} finally {
			try {
				if (fos != null){
					fos.close();
					fos = null;
				}
				if (bis != null){
					bis.close();
					bis = null;
				}
				if (httpUrl != null){
					httpUrl.disconnect();
					httpUrl = null;
				}
			} catch (Exception e) {
				throw e;
			}
		}
	}
}

